import { BadRequestException, Injectable } from '@nestjs/common';
import { CreateAuthDto } from './dto/create-auth.dto';
import { XC_MenuPermission, XC_Users } from './entities/auth.entity';
import { Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import * as bcryptjs from 'bcryptjs';
import { JwtService } from '@nestjs/jwt';

@Injectable()
export class AuthService {
  constructor(
    @InjectRepository(XC_Users) private readonly user: Repository<XC_Users>,
    @InjectRepository(XC_MenuPermission)
    private readonly menu: Repository<XC_MenuPermission>,
    private readonly jwtService: JwtService,
  ) {}

  // 注册
  async register(registerData: CreateAuthDto) {
    const findUser = await this.user.findOne({
      where: { username: registerData.username },
    });
    if (findUser && findUser.username === registerData.username)
      return '用户已存在';
    // 对密码进行加密处理
    registerData.password = bcryptjs.hashSync(registerData.password, 10);
    await this.user.save(registerData);
    return '注册成功';
  }

  // 登录
  async login(loginData: CreateAuthDto) {
    const findUser = await this.user.findOne({
      where: { username: loginData.username },
    });
    // 没有找到
    if (!findUser) throw new BadRequestException('用户不存在');

    // 找到了对比密码
    const compareRes: boolean = bcryptjs.compareSync(
      loginData.password,
      findUser.password,
    );
    // 密码不正确
    if (!compareRes) throw new BadRequestException('密码不正确');
    const payload = { username: findUser.username };

    return {
      token: this.jwtService.sign(payload),
      userInfo: { ...findUser, password: undefined },
      msg: '登录成功',
    };
  }

  // 获取目录信息
  async getMenuPermission() {
    return this.menu.find();
  }
}
